package com.korubo.conf;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.korubo.kit.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Slf4j
//HandlerInterceptor接口在   maven依赖spring-boot-starter-web
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //获取请求头中令牌
        String token = request.getHeader("X-Token");
        try {
            if (StrUtil.isBlank(token)) {
                map.put("msg", "签名不能为空!");
            } else {
                token = token.replaceAll("\"", "");
                token = JwtUtils.isTokenExpired(token);
                if (StrUtil.isBlank(token)) {
                    map.put("code", 401);
                } else {
                    response.setHeader("new_token", token);
                }
                //验证令牌
                DecodedJWT decodedJWT = JwtUtils.verifyToken(token);
                if (decodedJWT == null) {
                    throw new RuntimeException();
                }
                //验证成功，放行请求
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token无效!!");
            map.put("code", 401);
        }
        //设置状态
        map.put("state", false);
        //将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        // 相应json数据
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Expose-Headers", "new_token");
        response.getWriter().println(json);
        return false;
    }
}
